<template>
  <el-dialog :visible.sync="visible"
             :title="title"
             width="70%"
             :before-close="modalClose">
    <el-form :model="addForm"
             ref="addFormRef"
             :rules="addFormRules"
             label-width="150px"
             class="mt-20">
      <el-form-item label="检测项名称:"
                    prop="name">
        <el-input class="w-200"
                  placeholder="请填写检测项名称"
                  v-model="addForm.deviceName"></el-input>
      </el-form-item>
      <el-form-item label="图片："
                    prop="deviceImageUrl"
                    class="mt-20 upload-box">
        <el-upload class="avatar-uploader"
                   :action="uploadImgUrl"
                   :show-file-list="false"
                   :on-success="handleAvatarSuccess"
                   :before-upload="beforeAvatarUpload">
          <img v-if="addForm.deviceImageUrl"
               :src="addForm.deviceImageUrl"
               class="avatar" />
          <i v-else
             class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="前端排序:"
                    prop="sortNum">
        <el-input class="w-200"
                  placeholder="请输入排序"
                  v-model="addForm.sortNum"></el-input>
      </el-form-item>
      <el-form-item label="三甲医院名称:"
                    prop="hospitalName">
        <el-input type="textarea"
                  placeholder="请填写三甲医院名称"
                  :autosize="{ minRows: 4, maxRows: 8}"
                  style="width:50%"
                  v-model="addForm.hospitalName"></el-input>
      </el-form-item>
      <el-form-item label="其他医疗健康机构:"
                    prop="otherHospitalName">
        <el-input type="textarea"
                  placeholder="请填写其他医疗健康机构"
                  :autosize="{ minRows: 4, maxRows: 8}"
                  style="width:50%"
                  v-model="addForm.otherHospitalName"></el-input>
      </el-form-item>
      <el-form-item label="产学研资料:">
        <el-button type="primary"
                   @click="handleOption('add', null, tableData)">新 增</el-button>
        <el-table class="mt-20 table-layout"
                  border
                  :data="tableData">
          <el-table-column label="类型"
                           align="center">
            <template slot-scope="scope">
              <el-select v-model="scope.row.type"
                         placeholder="请选择类型">
                <el-option v-for="item in typeList"
                           :key="parseInt(item.type)"
                           :label="item.label"
                           :value="item.type"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="标题"
                           align="center"
                           prop="title">
            <template slot-scope="scope">
              <el-input v-model="scope.row.title"
                        class="w-200"
                        placeholder="请填写标题"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="内容"
                           align="center"
                           prop="content"
                           width="400">
            <template slot-scope="scope">
              <label v-if="scope.row.type === 1">
                <el-input type="textarea"
                          v-model="scope.row.content"
                          :autosize="{ minRows: 4, maxRows: 8}"
                          placeholder="请填写内容"></el-input>
              </label>
              <div v-else>
                <el-upload class="avatar-uploader"
                           :action="imageUploadUrl"
                           :on-remove="(file, fileList) => handleRemove(file, fileList, scope.$index)"
                           :file-list="scope.row.uploadFileList"
                           :on-success="(response, file, fileList) => handleSuccss(response, file, fileList, scope.$index)"
                           :list-type="scope.row.type === 2 ? 'picture-card' : 'text'"
                           :before-upload="file => beforeUpload(file, scope.row.type, scope.$index)">
                  <el-button size="small"
                             type="primary"
                             @click="handleClick (scope.row)">点击上传</el-button>
                </el-upload>
              </div>

            </template>
          </el-table-column>
          <el-table-column label="操作"
                           align="center"
                           width="120">
            <template slot-scope="scope">
              <el-button type="danger"
                         @click="handleOption('del', scope.$index, tableData)">删 除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
    <div class="mt-20 submit-btn">
      <el-button type="primary"
                 @click="submitForm()">提交</el-button>
      <el-button @click="modalClose">取消</el-button>
    </div>
  </el-dialog>
</template>
<script>
  export default {
    name: 'clinicalDialog',
    props: {
      visible: {
        type: Boolean,
        default: false
      },
      dataObj: {
        type: Object,
        default: false
      }
    },
    data () {
      return {
        title: '',
        uploadImgUrl: this.api.file.upload,
        imageUploadUrl: this.api.appUpgradeUpload.url,
        addForm: {
          id: null,
          deviceName: '', //
          deviceImageUrl: '',
          sortNum: '',
          hospitalName: '', // 三甲医院名称
          otherHospitalName: '', // 其他医疗机构名称
          researchDataDtos: [] // 研究资料数组
        },
        addFormRules: {
          deviceName: [
            { required: true, message: '请输入检测项名称', trigger: 'blur' }
          ],
          sortNum: [{ required: true, message: '请输入序号', trigger: 'blur' }]
        },
        tableData: [],
        typeList: [
          { type: 1, label: '链接' },
          { type: 2, label: '图片' },
          { type: 3, label: 'PDF' }
        ],
        uploadFileList: []
      };
    },
    methods: {
      // 关闭弹出框
      modalClose () {
        this.$emit('update:visible', false); // 直接修改父组件的属性
      },

      // 提交事件
      submitForm () {
        this.$refs.addFormRef.validate(async valid => {
          if (valid) {
            /* let item = this.tableData;
            if (item[item.length - 1].title === '') {
              this.$message.warning('请添写标题!');
              return;
            } */
            this.addForm.researchDataDtos = this.tableData.map(item => {
              if (item.type === 1) {
                return item;
              } else {
                return {
                  ...item,
                  content: typeof (item.content) === 'string' ? JSON.stringify([item.content]) : JSON.stringify(item.content)
                }
              }
            });
            const { data: res } = await this.post(this.api.clinical.editClinical, this.addForm);
            if (res.code === '200') {
              this.$message.success('保存成功');
              this.modalClose();
              this.$parent.getList();
            }
          }
        });
      },
      // 重置事件
      resetForm () {
        this.$refs.addFormRef.resetFields();
      },
      // 上传成功
      handleAvatarSuccess (response, file, fileList) {
        if (response.code === '200') {
          // 状态码为200时则上传成功
          this.addForm.deviceImageUrl = response.object[0];
          this.$message.success('上传成功!');
        } else {
          // 状态码不是200时上传失败 从列表中删除
          fileList.splice(fileList.indexOf(file), 1);
          this.$message.error(response.message);
        }
      },
      // 上传前的方法
      beforeAvatarUpload (file) {
        let types = ['image/jpeg', 'image/jpg', 'image/gif', 'image/png', 'image/bmp']
        const isType = types.includes(file.type);
        const isLt10M = file.size / 1024 / 1024 < 10;
        if (!isType) {
          this.$message.error('上传图片必须是JPG/JPEG/GIF/PNG/BMP 格式!');
          return isType;
        }
        if (!isLt10M) {
          this.$message.error('上传图片大小不能超过 10MB!');
          return isLt10M;
        }
      },
      // 上传前的方法
      beforeUpload (file, type, index) {
        let types = ['image/jpeg', 'image/jpg', 'image/gif', 'image/png', 'image/bmp']
        const isType = types.includes(file.type);
        let currType = file.type === 'application/pdf';
        if (type === 2) {
          if (!isType) {
            this.$message.error('上传图片必须是JPG/JPEG/GIF/PNG/BMP 格式!');
            return isType;
          }
        }
        if (type === 3) {
          if (!currType) {
            this.$message.error('上传附件必须是pdf 格式!');
            return currType;
          }
        }
      },
      //点击上传,打开对话框,此时暂存row数据
      handleClick (row) {
        //判断row.content是否已经传过数据
        if (row.content.length !== 0) {
          this.uploadFileList = Object.assign([], row.content);
        }

      },
      // 上传成功,push到当前行的content数组中
      handleSuccss (res, file, fileList, index) {
        if (res.code === '200') {
          // 状态码为200时则上传成功
          let uploadFileList = this.tableData[index].uploadFileList || [],
            content = this.tableData[index].content || [],
            temp = [];
          res.object.forEach(item => {
            temp.push({
              name: item,
              url: item
            })
          });
          this.tableData[index].content = [...res.object, ...content]
          this.tableData[index].uploadFileList = [...temp, ...uploadFileList];
          this.$message.success('上传成功');
        }
      },

      // 移除图片
      handleRemove (file, fileList, index = 0) {
        let key = 0, url = file.url;
        this.tableData[index].uploadFileList.forEach((item, index) => {
          if (item.url === url) {
            key = index;
          }
        });
        this.tableData[index].uploadFileList.splice(key, 1);
        this.tableData[index].content.splice(key, 1);
      },

      handleOption (op, index, table) {
        switch (op) {
          case 'add':
            if (table.length > 0 && table[table.length - 1].title === '') {
              this.$message.warning('请添写标题!');
              return;
            } else {
              table.push({
                id: null,
                type: 2,
                title: '',
                content: ''
              });
            }
            break;
          case 'del':
            table.splice(index, 1);
            break;
        }
      },

      // 详情
      async getDetail () {
        const { data: res } = await this.post(this.api.clinical.detailsClinical, { id: this.dataObj.id });
        if (res.code === '200') {
          this.addForm = res.object;
          this.tableData = res.object.researchDataDtos.map(item => {
            if (item.type === 1) {
              return item;
            } else {
              return {
                ...item,
                content: JSON.parse(item.content),
                uploadFileList: JSON.parse(item.content).map(v => ({
                  name: v,
                  url: v
                }))
              }
            }
          });
        }
      },
      // 获取最大序号
      async getMaxSortNum () {
        const { data: res } = await this.post(this.api.clinical.getMaxSortNum);
        if (res.code === '200') {
          this.addForm.sortNum = res.object.maxSortNum ? res.object.maxSortNum + 1 : 1;
        }
      }
    },
    created () {
      if (this.dataObj) {
        this.title = this.dataObj.deviceName;
        this.getDetail();
      } else {
        this.getMaxSortNum();
        this.title = '新 增';
      }
    }
  };
</script>
<style scoped lang="scss">
  .submit-btn {
    text-align: center;
  }
  .avatar-uploader /deep/.el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .upload-box {
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
  }

  .table-layout {
    /deep/ .el-upload {
      width: 100px;
      height: 100px;
      line-height: 100px;
      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        text-align: center;
      }
    }
  }
</style>
